package cn.liccshop.core.proscenium.shopUser.controller;


import cn.liccshop.core.entity.ShopUser;
import cn.liccshop.core.proscenium.shopUser.service.IShopUserService;
import cn.liccshop.core.utils.ObjectToOtherUtils;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.entity.Result;
import cn.liccshop.sys.entity.UserElement;
import cn.liccshop.sys.exception.MySystemException;
import cn.liccshop.sys.utils.RandomNumberCode;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.liccshop.sys.base.MyActionController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 消费者用户表 前端控制器
 *
 * @author LiCC
 * @since 2019-04-28
 */
@RestController
@RequestMapping("/shopUser")
public class ShopUserController extends MyActionController<ShopUser> {

    @Autowired
    private IShopUserService liShopUserService;

    @Override
    protected IService<ShopUser> getLiService(){
        return liShopUserService;
    }

    @RequestMapping(value = "/login")
    public Result login(@RequestBody ShopUser user) throws MySystemException {
        if (StringUtils.isBlank(user.getPhone())||StringUtils.isBlank(user.getPassword())){
            /** 手机号或者密码为空 **/
            throw new MySystemException("登录名或密码有误！", Constants.INVALID_PARM);
        }
        ShopUser data = liShopUserService.login(user);
        return new Result().setCode(Constants.OK).setData(data).setMessage("登录成功");
    }
    @RequestMapping("info")
    public Result getUserInfo() throws MySystemException {
        String userId = getUserInfoByToken().getUserId();
        if (StringUtils.isBlank(userId)){
            throw new MySystemException("用户未登陆",Constants.UNAUTHEN);
        }
        ShopUser data = liShopUserService.getUserInfo(userId);
        return new Result().setMessage("成功获取用户信息").setData(data).setCode(Constants.OK);
    }

    /**
     * 用户注册
     * @param shopUser
     * @return
     */
    @RequestMapping("/register")
    public Result registerInfo(@RequestBody ShopUser shopUser) throws MySystemException {
        shopUser.setNickname("shop"+ RandomNumberCode.getUserCode())
                .setPhoto(Constants.SHOP_USER_HEADER_IMG)
                .setSex(Constants.SHOP_USER_SEX)
                .setAge(LocalDateTime.parse(Constants.SHOP_USER_AGE, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .setDisabled(1);
        boolean isSuccess = liShopUserService.registerInfo(shopUser);
        return isSuccess ? new Result().setMessage("注册成功").setCode(Constants.OK)
                :new Result().setMessage("注册失败").setCode(Constants.FAIL);
    }

    /**
     * 用户重置密码
     * @param user
     * @return
     */
    @RequestMapping(value = "/restPassword")
    public Result restPassword(@RequestBody ShopUser user) throws MySystemException {
        boolean isSuccess = liShopUserService.restPassword(user);
        return isSuccess ? new Result().setMessage("重置成功").setCode(Constants.OK)
                :new Result().setMessage("重置失败").setCode(Constants.FAIL);
    }
    /**
     * 用户请求短信验证码
     * phone,type(1:注册；2:重置)
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "sendVercode")
    public Result sendVercode(@RequestBody Map<String, Object> map, HttpServletRequest request) throws MySystemException {
        String phone = ObjectToOtherUtils.toString(map.get("phone"));
        Integer type = ObjectToOtherUtils.toInteger(map.get("type"));
        if (StringUtils.isBlank(phone)){
            throw new MySystemException("请输入手机号", Constants.INVALID_PARM);
        }
        ShopUser shopUser = liShopUserService.getOne(new QueryWrapper<>(new ShopUser().setPhone(phone)));
        if (type==1){
            /** 注册： **/
            if (shopUser!=null){
                throw new MySystemException("该手机号已注册",Constants.INVALID_PARM);
            }
        } else if (type==2){
            /** 重置密码 **/
            if (shopUser==null){
                throw new MySystemException("该手机号还未注册",Constants.INVALID_PARM);
            }
        } else {
            throw new MySystemException("短信类型参数错误",Constants.SERVICE_FAIL);
        }
        liShopUserService.sendVercode(phone, getIpFromRequest(request));
        return new Result().setMessage("短信发送成功，请等待").setCode(Constants.OK);
    }

    /**
     * 超级管理员获取所有消费者信息
     * @param page
     * @param size
     * @param map
     * @return
     */
    @RequestMapping(value = "/allInfo")
    public Result getUserAllInfo(@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestBody Map<String, Object> map){
        IPage<ShopUser> iPage = new Page<>(page, size);
        Wrapper<ShopUser> wrapper = new QueryWrapper<>(new ShopUser()).orderByAsc("create_date");
        if (map.get("phone")!=null){
            /** 手机号存在 **/
            ((QueryWrapper<ShopUser>) wrapper).like("phone",map.get("phone"));
        }
        if (map.get("date")!=null){
            /** 筛选时间数据存在 **/
            String[] date = ObjectToOtherUtils.toString(map.get("date")).split(",");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            ((QueryWrapper<ShopUser>) wrapper).between("create_date",LocalDateTime.parse(date[0],df),LocalDateTime.parse(date[1],df));
        }
        liShopUserService.page(iPage, wrapper);
        return new Result().setCode(Constants.OK).setData(iPage);
    }

    /**
     * 通过性别统计用户数量
     * @return
     */
    @RequestMapping(value = "countGroupBySex")
    public Result getCountGroupBySex(){
        Map<String, Object> data = liShopUserService.getCountGroupBySex();
        return new Result().setCode(Constants.OK).setData(data).setMessage("获取信息成功");
    }

}

